package com.kingdee.openimport.patch_service.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Set;

/**
 * Redis哨兵配置
 * Created by Niki on 2018/4/21 15:00
 */
@Configuration
@Slf4j
public class JedisConfig {

    @Value("${spring.redis.sentinel.master}")
    private String masterName;
    @Value("${spring.redis.sentinel.nodes}")
    private String nodes;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive ;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public JedisSentinelPool redisSentinelPool() {
        JedisSentinelPool pool = null;
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxActive);

        Set<String> sentinels = getSentinels(nodes);
        if (StringUtils.isEmpty(password)) {
            pool = new JedisSentinelPool(masterName, sentinels, config, timeout);
        } else {
            pool = new JedisSentinelPool(masterName, sentinels, config, timeout, password);
        }
        return pool;
    }

    private Set<String> getSentinels(String sentinelNodeStr) {
        Set<String> sentinels = new HashSet<>();
        if (sentinelNodeStr != null) {
            String[] sentinelArr = sentinelNodeStr.split(",");
            if (sentinelArr != null) {
                for (String sen : sentinelArr) {
                    if (sen != null) {
                        sentinels.add(sen);
                    }
                }
            }
        }
        return sentinels;
    }
}
